﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Text;
using System.Data.SqlClient;

public partial class order_contact : BasePage
{

    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            lblError.Text = "";
            return;
        }
        butNext.Attributes.Add("onclick", "javascript:return confirm('Are you sure?');");
        try
        {
            DateTime DepTime, ArrTime, LastArrTime;
            TimeSpan span;// = new TimeSpan(0, 0, 0);
            int link_time;
            string sTmp;
            string[] sSplited;
            int adt_count, chd_count, inf_count, trip_count;

            
            if (Session["TRIP_COUNT"] == null)
            {
                butNext.Enabled = false;
                lblError.Text = "Illegal Post!";
                return;
            }
            trip_count = Convert.ToInt16(Session["TRIP_COUNT"].ToString());
            adt_count = Convert.ToInt16(Session["ADT_COUNT"].ToString());
            chd_count = Convert.ToInt16(Session["CHD_COUNT"].ToString());
            inf_count = Convert.ToInt16(Session["INF_COUNT"].ToString());
            lblAdtCount.Text = adt_count.ToString();
            lblChdCount.Text = chd_count.ToString();
            lblInfCount.Text = inf_count.ToString();

            LastArrTime = Convert.ToDateTime("1900-1-1");
            for (int i = 1; i <= trip_count; i++)
            {
                sTmp = Request.Form["KEY" + i.ToString()];
                if (sTmp == null)
                {
                    lblError.Text = "Please select your desired fare for each trip segment.";
                    butNext.Enabled = false;
                    return;
                }
                //check link time....
                sSplited = sTmp.Split('|');

                Session["FLT_DATE" + i.ToString()] = sSplited[0];
                Session["FLT_NO" + i.ToString()] = sSplited[2];
                Session["AIRLINE" + i.ToString()] = sSplited[1];
                Session["ORI" + i.ToString()] = sSplited[3];//airport!not city!
                Session["DES" + i.ToString()] = sSplited[4];
                Session["CABIN" + i.ToString()] = sSplited[5];
                Session["CLASS" + i.ToString()] = sSplited[6];
                Session["FARE" + i.ToString()] = sSplited[7];
                Session["DBF" + i.ToString()] = sSplited[11];

                DepTime = Convert.ToDateTime(sSplited[9]);
                ArrTime = Convert.ToDateTime(sSplited[10]);
                //if (sSplited[8] == "1")//domestic = true;
                //{
                //    link_time = Convert.ToInt16(sSplited[11]);
                //}
                //else
                //{
                //    link_time =  Convert.ToInt16(sSplited[12]);
                //}
                link_time = 30;//前置检查至少要求提前半小时衔接？=系统最低衔接时间
                span = new TimeSpan(0, link_time, 0);
                if (i > 1)//need to check link time
                {
                    if (DepTime - LastArrTime < span)
                    {
                        lblError.Text = sSplited[3] + "-" + sSplited[4] + "衔接时间不够，请更换航班！";
                        butNext.Enabled = false;
                        break;
                    }
                }
                LastArrTime = ArrTime;
            }
        }
        catch (Exception ex)
        {
            lblError.Text = ex.Message;
        }
    }

    protected void butNext_Click(object sender, EventArgs e)
    {
        txtContactMan.Text = txtContactMan.Text.Trim();
        txtMobilePhone.Text = txtMobilePhone.Text.Trim();
        if (txtContactMan.Text == "")
        {
            lblError.Text = "Please fill contact info!";
            return;
        }
        if (txtMobilePhone.Text == "")
        {
            lblError.Text = "Please fill contact info!";
            return;
        }

        long new_id;
        int i, ret_code;
        string ret_msg;
        int adt_count, chd_count, inf_count, trip_count;
        StringBuilder open_buf = new StringBuilder("", 10);
        StringBuilder fltno_buf = new StringBuilder("", 30);
        StringBuilder fltdate_buf = new StringBuilder("", 100);
        StringBuilder airline_buf = new StringBuilder("", 20);
        StringBuilder ori_buf = new StringBuilder("", 20);
        StringBuilder des_buf = new StringBuilder("", 20);
        StringBuilder cabin_buf = new StringBuilder("", 10);
        StringBuilder class_buf = new StringBuilder("", 10);
        StringBuilder fare_buf = new StringBuilder("", 50);
        StringBuilder dbf_buf = new StringBuilder("", 50);
        //TinyDAL dal = new TinyDAL();

        //此处用Session保存是为了方便用户重新选航班日期订座，再次进入时用上次输入的信息
        adt_count = Convert.ToInt16(lblAdtCount.Text);
        chd_count = Convert.ToInt16(lblChdCount.Text);
        inf_count = Convert.ToInt16(lblInfCount.Text);
        //Session["ADT_COUNT"] = adt_count;
        //Session["CHD_COUNT"] = chd_count;
        //Session["INF_COUNT"] = inf_count;

        //Session["CONTACT_MAN"] = txtContactMan.Text;
        //Session["MOBILE"] = txtMobilePhone.Text;
        //Session["PHONE"] = txtPhone.Text;
        //Session["ADDRESS"] = txtAddress.Text;
        //Session["EMAIL"] = txtEmail.Text;
        //Session["POST_CODE"] = txtPostCode.Text;


        try
        {
            //SqlCommand cmd = new SqlCommand(/*"sp_get_trans_id", conn*/);
            //cmd.CommandText = "sp_get_bk_id";//"sp_get_trans_id";
            ////SqlParameter paraDate = new SqlParameter("@reset_date", SqlDbType.DateTime);
            ////paraDate.Direction = ParameterDirection.Output;
            ////cmd.Parameters.Add(paraDate);
            //SqlParameter paraID = new SqlParameter("@curr_id", SqlDbType.BigInt);
            //paraID.Direction = ParameterDirection.Output;
            //cmd.Parameters.Add(paraID);
            //SqlParameter para = cmd.Parameters.AddWithValue("@office", Session["OFFICE"].ToString());
            //para = cmd.Parameters.AddWithValue("@entity", Session["ENTITY"].ToString());
            //para = cmd.Parameters.AddWithValue("@user", Session["USER"].ToString());
            //para = cmd.Parameters.AddWithValue("@ip_addr", Request.UserHostAddress.ToString());
            //TinyDAL.Exec(ref cmd);
            //new_id = System.Convert.ToInt64(paraID.Value);
            //if (new_id < 0)
            //{
            //    lblError.Text = "System is busy. Retry please.";
            //    return;
            //}
            ////mod = new_id % 7;//目前检查重复的任务在存储过程中（同时负责计算校验码，下面代码可省），负担加大，是否不合理？
            //Session["BK_ID"] = new_id;// *10 + mod;//记录最后一次访问的订单号

            //string pwd_sha1 = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(Application["PWD"].ToString(), "SHA1");
            string sign;

            CRSI.Order nOrder = new CRSI.Order();
            trip_count = Convert.ToInt16(Session["TRIP_COUNT"].ToString());
            for (i = 1; i <= trip_count; i++)
            {
                //open_buf.Append(Session["OPEN" + i.ToString()] + ",");
                fltdate_buf.Append(Session["FLT_DATE" + i.ToString()] + ",");
                fltno_buf.Append(Session["FLT_NO" + i.ToString()] + ",");
                airline_buf.Append(Session["AIRLINE" + i.ToString()] + ",");
                ori_buf.Append(Session["ORI" + i.ToString()] + ",");
                des_buf.Append(Session["DES" + i.ToString()] + ",");
                cabin_buf.Append(Session["CABIN" + i.ToString()] + ",");
                class_buf.Append(Session["CLASS" + i.ToString()] + ",");
                fare_buf.Append(Session["FARE" + i.ToString()] + ",");
                dbf_buf.Append(Session["DBF" + i.ToString()] + ",");

            }
            sign = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(fltdate_buf + "|" + fltno_buf + "|" + class_buf + "|" + fare_buf + "|" + Application["HASH_PWD"].ToString(), "MD5");
            ret_code=nOrder.New(trip_count,adt_count,chd_count,inf_count,txtContactMan.Text,txtMobilePhone.Text,
            txtPhone.Text,txtEmail.Text,"",'C',airline_buf.ToString(),fltno_buf.ToString(),
            fltdate_buf.ToString(),ori_buf.ToString(),des_buf.ToString(),cabin_buf.ToString(),class_buf.ToString(),
            fare_buf.ToString(), dbf_buf.ToString(), Application["UID"].ToString(), sign, out new_id, out ret_msg);
            if (ret_code < 0)
            {
                lblError.Text = ret_msg;
                return;
            }

            switch (ret_code)
            {
                case 0:
                    //未提交订单现在保存，否则丢失联系人信息！
                    //save to local database!
                    SqlCommand cmd = new SqlCommand();
                    cmd.CommandText = "save_local_order";
                    SqlParameter para = cmd.Parameters.AddWithValue("@uid", Session["UID"].ToString());
                    para = cmd.Parameters.AddWithValue("@order_no", new_id);
                    para = cmd.Parameters.AddWithValue("@contact", txtContactMan.Text);
                    para = cmd.Parameters.AddWithValue("@mobile_phone", txtMobilePhone.Text);
                    para = cmd.Parameters.AddWithValue("@email", txtEmail.Text);
                    ret_code = TinyDAL.Exec(ref cmd);
                    if (ret_code != 0)
                    {
                        lblError.Text = "保存订单出错";//用户看不见！
                        return;
                    }
                    Response.Redirect("pax_list.aspx?pnr=" + new_id.ToString() + "&is_new=T");
                    break;
                case 1:
                    lblError.Text = "1:Too many trips!(Max=4)";
                    break;
                case 2:
                    lblError.Text = "2:Improper use of fare! Lost starting.";
                    break;
                case 3:
                    lblError.Text = "3:Improper use of fare! Lost ending.";
                    break;
                case 4:
                    lblError.Text = "4:Illegal use of fare!";
                    break;
                case 5:
                    lblError.Text = "5:Improper use of fare! Lost middle.";
                    break;
                case 6:
                    lblError.Text = "6:Too many passengers!";
                    break;
                case 20:
                    lblError.Text = "20:Flight not found or invalid status!";
                    break;
                case 22:
                    lblError.Text = "22:Origin city day-light-saving info not found!";
                    break;
                case 24:
                    lblError.Text = "24:Flight not open yet!";
                    break;
                case 25:
                    lblError.Text = "25:Airport link time info not found!";
                    break;
                case 29:
                    lblError.Text = "29:Stay days not satisfied!";
                    break;
                case 49:
                    lblError.Text = "49:Fare not found!";
                    break;
                case 100:
                    lblError.Text = "100:Adding new order failed!";
                    break;
                case 101:
                    lblError.Text = "101:Updating class failed!";
                    break;
                case 102:
                    lblError.Text = "102:Updating cabin failed!";
                    break;
                case 103:
                    lblError.Text = "103:Add block order trip failed!";
                    break;
                case 104:
                    lblError.Text = "104:Cabin not found!";
                    break;
                case 105:
                    lblError.Text = "105:Class not found!";
                    break;
                case 106:
                    lblError.Text = "106:Class blocked!";
                    break;
                case 107:
                    lblError.Text = "107:Request only!";
                    break;
                case 109:
                    lblError.Text = "109:No sufficient seats!";
                    break;
                case 110:
                    lblError.Text = "110:Standing-by request failed!";
                    break;
                case 111:
                    lblError.Text = "111:Blocking cabin failed!";
                    break;
                case 112:
                    lblError.Text = "112:Blocking class failed!";
                    break;
                case 113:
                    lblError.Text = "113:Add order trip failed!";
                    break;
                case 114:
                    lblError.Text = "114:Flight not found!";
                    break;
                case 150:
                    lblError.Text = "150:Re-calculate nested available seats failed!";
                    break;
                case 200:
                    lblError.Text = "200:No sufficient seats!";
                    break;
                case 201:
                    lblError.Text = "201:Class not found!";
                    break;
                case 202:
                    lblError.Text = "202:Insufficient nested seats";
                    break;
                case 203:
                    lblError.Text = "203:Nesting class seats failed!";
                    break;
                case 204:
                    lblError.Text = "204:Nesting class seats failed!";
                    break;
                case 300:
                case 301:
                case 302:
                case 303:
                case 304:
                case 305:
                case 306:
                case 307:
                    lblError.Text = ret_code.ToString() + ":Illegal request data!";
                    break;
                default:
                    lblError.Text = "Unknown error:" + ret_code.ToString();
                    break;
            }



            //pnr_int mypnr = new pnr_int();
            //lblError.Text = "Your order number is " + mypnr.int2pnr(new_id * 10 + mod) + "/" + (new_id * 10 + mod).ToString();






        }
        catch (Exception ex)
        {
            lblError.Text = ex.Message;

        }
    }
}
